﻿#if NET45_OR_GREATER
using System.Collections.Concurrent;
using System.Reflection;

namespace zijian666.Extensions;

internal static class AssemblyExtensions
{
    private static readonly ConcurrentDictionary<string, IList<Assembly>> _cache = new();

    /// <summary>
    /// 从指定路径载入所有程序集
    /// </summary>
    /// <param name="domain"></param>
    /// <param name="path"></param>
    /// <returns></returns>
    public static IList<Assembly> LoadAllAssemblies(this AppDomain domain, string path) =>
        _cache.GetOrAdd(path, p =>
        {
            var dm = AppDomain.CreateDomain("temp");

            foreach (var dll in Directory.GetFiles(p, "*.dll", SearchOption.AllDirectories))
            {
                try
                {
                    var ass = dm.Load(File.ReadAllBytes(dll));
                    _ = domain.Load(ass.GetName());
                }
                catch (Exception) { }
            }

            AppDomain.Unload(dm);
            return domain.GetAssemblies().ToList().AsReadOnly();
        });

    /// <summary>
    /// 载入所有程序集
    /// </summary>
    /// <param name="domain"></param>
    /// <returns></returns>
    public static IList<Assembly> LoadAllAssemblies(this AppDomain domain) =>
        domain.LoadAllAssemblies(domain.BaseDirectory);

}

#endif